<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\api\services\Config as configService;
use think\Db;
use think\Exception;
use think\exception\HttpException;
use think\Log;

/**
 * 关键词百度PC排名
 */
class RankStr extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];


    /**
     * 关键词百度PC排名----单进程
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index(){
        set_time_limit(0);
        $page = $this->request->param('page',1);
        $kuaipai_id = $this->request->param('id',0);

        set_time_limit(0);
        $timeout = [
            'http'=>[
                'timeout'=>5
            ]
        ];
        $ctx = stream_context_create($timeout);
        $key = 'abba29bd462f45c8b5339ce8001fdbda';
        $api_url = 'https://apidatav2.chinaz.com/single/baidupc/keywordranking?key='.$key;
        $i = 0;

        if($kuaipai_id){
            $kuaipai_config_data = Db::name('task_config')
                ->where('Id','=',$kuaipai_id)
                ->where('params_type_id','=',4)
                ->where('Status','=',1)
                ->where('ranking_sign','=',0)
                ->where('Name','<>','')
                ->where('TargetUrl','<>','')
                ->page($page,50)->select();
        }else{
            $kuaipai_config_data = Db::name('task_config')
                ->where('params_type_id','=',4)
                ->where('Status','=',1)
                ->where('ranking_sign','=',0)
                ->where('Name','<>','')
                ->where('TargetUrl','<>','')
                ->page($page,50)->select();
        }

        if(!$kuaipai_config_data){
            return '快排关键词不存在';
        }

        foreach($kuaipai_config_data as $k=>$v){
            $data['task_config_id'] = $v['Id'];
            $data['task_config_name'] = $v['Name'];
            $data['create_date'] = date('Y-m-d');
            $api_url_2 = $api_url.'&domain='.$v['TargetUrl'].'&keyword='.$v['Name'];
            try{
//                $get_res = file_get_contents($api_url_2,0,$ctx);
                $get_res = curl_get($api_url_2);
            }catch(Exception $e){
                Log::info('关键词百度PC排名---curl_get----捕捉异常---');
                Log::info(date('Y-m-d H:i:s'));
                Log::info($e->getMessage());
                continue;
            }
            $data['detail'] = $get_res;
            Log::info('curl_get-----返回json数据----------'.$get_res);
            if($get_res){
                $json_arr = json_decode($get_res,true);
                if($json_arr['StateCode'] == 1){
//                    dump($json_arr['Result']['Ranks'][0]['RankStr']);die;
                    if(isset($json_arr['Result']['Ranks'][0]['RankStr'])){
                        $RankStr_str = '';
                        foreach($json_arr['Result']['Ranks'] as $k2=>$v2){
                            if($v['TargetUrl'] == $v2['Url']){
                                $RankStr_str = $v2['RankStr'];
                            }
                        }
                        if(empty($RankStr_str)){
                            $data['rank_str'] = $json_arr['Result']['Ranks'][0]['RankStr'];
                        }else{
                            $data['rank_str'] = $RankStr_str;
                        }
                    }else{
                        Log::info('关键词百度PC排名---失败------RankStr字段不存在---');
                        Log::info($v['Id']);
                        Log::info($v['Name']);
                        Log::info($get_res);
                        $data['rank_str'] = '-';
                    }
                }else{
                    Log::info('关键词百度PC排名---失败--StateCode-----不是1----');
                    Log::info($v['Id']);
                    Log::info($v['Name']);
                    Log::info($get_res);
                    $data['rank_str'] = '-';
                }
            }else{
                Log::info('关键词百度PC排名---失败---接口未响应---');
                Log::info($v['Id']);
                Log::info($v['Name']);
                Log::info($get_res);
                $data['rank_str'] = '-';
            }

            $has = Db::name('rank_str')->where('task_config_id','=',$v['Id'])->where('create_date','=',date('Y-m-d'))->find();

            if($has){
                Db::name('rank_str')->where('task_config_id','=',$v['Id'])->where('create_date','=',date('Y-m-d'))->delete();
            }

            Db::name('rank_str')->insert($data);
            $update_data['ranking_sign'] = 1;
            Db::name('task_config')->where('Id','=',$v['Id'])->update($update_data);
            $i += 1;


        }

        return '关键词百度PC排名----统计成功-----'.date('Y-m-d').'-----------更新数量：'.$i.'--------------------';

    }

    //TODO:关键词百度PC排名----多进程
    public function index2(){
        $kuaipai_count_total =  Db::name('task_config')
            ->where('params_type_id','=',4)
            ->where('ranking_sign','=',0)
            ->where('Name','<>','')
            ->where('TargetUrl','<>','')
            ->count();
        $fork_number = ceil($kuaipai_count_total/20);
        for ($i = 1; $i <= $fork_number; $i++){
            $pid = pcntl_fork();
            if ($pid == -1) {
                die("could not fork");
            } elseif ($pid) {
                echo $pid;
                echo "I'm the Parent $i\n";
            } else {
                // 子进程处理
                $timeout = ['http'=>['timeout'=>5]];
                $ctx = stream_context_create($timeout);
                $key = 'abba29bd462f45c8b5339ce8001fdbda';
                $api_url = 'https://apidatav2.chinaz.com/single/baidupc/keywordranking?key='.$key;
                $kuaipai_config_data = Db::name('task_config')
                    ->where('params_type_id','=',4)
                    ->where('ranking_sign','=',0)
                    ->where('Name','<>','')
                    ->where('TargetUrl','<>','')
                    ->page($i,20)->select();
                $complate_count = 0;
                try{
                    foreach($kuaipai_config_data as $k=>$v){
                        $data['task_config_id'] = $v['Id'];
                        $data['task_config_name'] = $v['Name'];
                        $data['create_date'] = date('Y-m-d');
                        if($v['Name'] && $v['TargetUrl']){
                            $api_url_2 = $api_url.'&domain='.$v['TargetUrl'].'&keyword='.$v['Name'];
                            $get_res = file_get_contents($api_url_2,0,$ctx);
                            if($get_res){
                                $json_arr = json_decode($get_res,true);
                                if($json_arr['StateCode'] == 1){
                                    if(isset($json_arr['Result']['Ranks'][0]['RankStr'])){
                                        $data['rank_str'] = $json_arr['Result']['Ranks'][0]['RankStr'];
                                    }else{
                                        Log::info('关键词百度PC排名---失败------RankStr字段不存在---');
                                        Log::info($v['Id']);
                                        Log::info($v['Name']);
                                        Log::info($get_res);
                                        $data['rank_str'] = '-';
                                    }
                                }else{
                                    Log::info('关键词百度PC排名---失败--StateCode-----不是1----');
                                    Log::info($v['Id']);
                                    Log::info($v['Name']);
                                    Log::info($get_res);
                                    $data['rank_str'] = '-';
                                }
                            }else{
                                Log::info('关键词百度PC排名---失败---接口未响应---');
                                Log::info($v['Id']);
                                Log::info($v['Name']);
                                Log::info($get_res);
                                $data['rank_str'] = '-';
                            }
                        }else{
                            Log::info('关键词百度PC排名---失败----Name或者TargetUrl不存在----');
                            Log::info($v['Id']);
                            Log::info($v['Name']);
                            $data['rank_str'] = '-';
                        }
                        $has = Db::name('rank_str')->where('task_config_id','=',$v['Id'])->where('create_date','=',date('Y-m-d'))->find();
                        if($has){
                            Db::name('rank_str')->where('task_config_id','=',$v['Id'])->where('create_date','=',date('Y-m-d'))->delete();
                        }
                        Db::name('rank_str')->insert($data);
                        $complate_count += 1;
                    }
                }catch(Exception $e){
                    Log::info('关键词百度PC排名---捕捉异常---');
                    Log::info(time());
                    Log::info($e->getMessage());
                }
                unset($list);

                // $content = file_get_contents("prefix_name0".$i);
//                $psum = array_sum($arrint[$i]);
                echo '----数量----'.$complate_count . "\n";  //分别输出子进程的部分求和数字，但是无法进行相加，因为进程互相独立
                exit;               //一定要注意退出子进程,否则pcntl_fork() 会被子进程再fork,带来处理上的影响。
            }
        }

        // 等待子进程执行结
        while (pcntl_waitpid(0, $status) != -1) {
            $status = pcntl_wexitstatus($status);
            echo "Child $status completed\n";
        }

    }


    /**
     * 将ranking_sign字段全部更新为初始值0-----每天夜里12点执行----定时计划任务
     * @throws Exception
     * @throws \think\exception\PDOException
     */
    public function update_ranking_sign(){
        $update_data['ranking_sign'] = 0;
        Db::name('task_config')->where(['params_type_id'=>4])->update($update_data);
        echo '将ranking_sign字段全部更新为初始值0----成功-------';
    }

    public function cache_rank_str(){

    }







}
